package com.hd.crdao.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hd.crdao.R;
import com.hd.crdao.base.MyBaseAdapter;
import com.hd.crdao.bean.AreaListBean;
import com.hd.crdao.utils.UIUtils;

import java.util.List;

/**
 *
 *@author Administrator
 *@date 2017/5/31 0031
 */
public class ProvinceAdapter extends MyBaseAdapter<AreaListBean.ListAreaBean> {

    public ProvinceAdapter(List<AreaListBean.ListAreaBean> dataSets) {
        super(dataSets);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ProvinceAdapter.ViewHolder viewHolder;
        AreaListBean.ListAreaBean listAreaBean = mDataSets.get(position);
        if (convertView == null) {
            viewHolder = new ProvinceAdapter.ViewHolder();
            convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.item_province, null);
            viewHolder.name = (TextView) convertView.findViewById(R.id.name);
            viewHolder.catalog = (TextView) convertView.findViewById(R.id.catalog);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ProvinceAdapter.ViewHolder) convertView.getTag();
        }

        //根据position获取首字母作为目录catalog
        String catalog = listAreaBean.getNamepy();

        //如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
        if(position == getPositionForSection(catalog)){
            viewHolder.catalog.setVisibility(View.VISIBLE);
            viewHolder.catalog.setText(listAreaBean.getNamepy());
        }else{
            viewHolder.catalog.setVisibility(View.GONE);
        }

        viewHolder.name.setText(listAreaBean.getName());

        return convertView;

    }

    final static class ViewHolder {
        TextView catalog;
        TextView name;
    }
    /**
     * 获取catalog首次出现位置
     */
    public int getPositionForSection(String catalog) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = mDataSets.get(i).getNamepy();
            if (catalog.equalsIgnoreCase(sortStr)) {
                return i;
            }
        }
        return -1;
    }
}
